import { Injectable } from '@angular/core';
import {
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor,
    HttpErrorResponse,
} from '@angular/common/http';

import { Router } from '@angular/router';
import { Observable, tap, finalize, catchError, map, throwError } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd/message';

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {

    constructor(private message: NzMessageService, private router: Router) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token = localStorage.getItem('jwt') ?? '';
        request = request.clone({
            setHeaders: {
                AccessToken: token
            }
        });
        return next.handle(request).pipe(
            map(event => {
                return event;
            }),
            catchError((err, caught) => this.handleError(err)),
            finalize(() => { })
        )
    }

    private handleError(err: HttpErrorResponse): Observable<never> {
        if (err.status === 401) {
            // not authorized so redirect to login page with the return url
            this.router.navigate(['/login'], {
                queryParams: { returnUrl: this.router.url }
            });
        }
        this.message.create('error', `${err.status}:${err.statusText}`, { nzDuration: 3000 });
        return throwError(() => err);
    }
}
